<template>
  <view class="container">
    <!-- 搜索和筛选区域 -->
    <view class="filter-section">
      <view class="search-bar">
        <input 
          class="search-input" 
          v-model="queryParams.name" 
          placeholder="搜索陪诊师" 
          placeholder-style="color: #999;"
          @input="handleSearchInput"
      @confirm="handleSearchConfirm"
        />
        <button class="search-btn" @click="loadTherapists">搜索</button>
      </view>
      <view class="date-time-picker">
        <picker 
          mode="date" 
          :value="queryParams.selectedDate" 
          @change="onDateChange"
          class="picker-item"
        >
          <view class="picker-content">
            <text class="picker-label">日期</text>
            <text class="picker-value">{{ queryParams.selectedDate || '请选择' }}</text>
          </view>
        </picker>
        <picker 
          mode="time" 
          :value="queryParams.selectedTime" 
          @change="onTimeChange"
          class="picker-item"
        >
          <view class="picker-content">
            <text class="picker-label">时间</text>
            <text class="picker-value">{{ queryParams.selectedTime || '请选择' }}</text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 陪诊师列表 -->
    <view class="therapist-list">
      <view 
        v-for="therapist in therapistList" 
        :key="therapist.id" 
        class="therapist-card"
      >
        <view class="therapist-info">
          <view class="basic-info">
            <text class="name">{{ therapist.name }}</text>
            <text class="tag">{{ formatGender(therapist.gender) }}</text>
            <text class="tag">{{ therapist.age }}岁</text>
          </view>
          <view class="contact-info">
            <text class="phone">联系电话：{{ therapist.phone }}</text>
          </view>
        </view>
        <view class="action-area">
          <button
            class="action-btn"
            :class="{
              'btn-disabled': isReserved(therapist),
              'btn-booked': hasBooked(therapist),
              'btn-primary': !hasBooked(therapist) && !isReserved(therapist)
            }"
            :disabled="isReserved(therapist)"
            @click="handleBooking(therapist)"
          >
            {{ getButtonText(therapist) }}
          </button>
        </view>
      </view>
    </view>

    <!-- 提示弹窗 -->
    <uni-popup 
      v-model:show="isPopupVisible"
      type="center"
    >
      <view class="popup-content">
        <text class="popup-message">{{ popupMessage }}</text>
        <button class="popup-btn" @click="closePopup">确定</button>
      </view>
    </uni-popup>

    <!-- 用户名输入弹窗 -->
    <uni-popup 
      v-model:show="isUsernamePopupVisible"
      type="center"
    >
      <view class="popup-content">
        <input 
          v-model="usernameInput" 
          placeholder="请输入用户名" 
          class="popup-input"
        />
        <view class="popup-buttons">
          <button class="popup-btn btn-primary" @click="confirmBooking">确认预约</button>
          <button class="popup-btn btn-default" @click="isUsernamePopupVisible = false">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  listRelation,
  addRelation,
  delRelation,
  getUserIdByUsername
} from '@/api/system/relation.js';
import {
  listTherapist,
  getAccompanyingTherapistByIsadmin
} from '@/api/peizhenshi.js';
import {
  isValidDate,
  isValidTime
} from '@/utils/formatDateTime';
import { getToken, removeToken } from '@/utils/auth';

export default {
  data() {
    return {
      isPopupVisible: false,
      isUsernamePopupVisible: false,
      popupMessage: '',
      usernameInput: '',
      selectedTherapist: null,
      therapistList: [],
      relationList: [],
      queryParams: {
        name: '',
        selectedDate: '',
        selectedTime: ''
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      refreshing: false,
      searchTimer: null,
    };
  },
  mounted() {
    this.checkLoginAndLoadData();

    // 监听预约成功事件
    uni.$on('bookingConfirmed', async (data) => {
      this.relationList.push({
        ...data,
        id: Date.now()
      });
      this.showPopup('预约成功');
    });
  },
  methods: {
    methods: {
  // 防抖处理搜索
  handleSearchInput() {
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    this.searchTimer = setTimeout(() => {
      this.loadTherapists();
    }, 500); // 500ms 防抖
  },

  // 回车触发搜索
  handleSearchConfirm() {
    this.handleSearch();
  },

  // 点击搜索按钮
  async handleSearch() {
    if (this.loading) return;
    this.page.pageNum = 1;
    await this.loadTherapists();
  },

  // 加载陪诊师数据
  async loadTherapists() {
    const query = {
      pageNum: this.page.pageNum,
      pageSize: this.page.pageSize,
      name: this.queryParams.name.trim()
    };

    try {
      const res = await listTherapist(query); // 后续由后端根据 name 过滤

      if (res.code === 200) {
        this.therapistList = res.rows.map(item => ({
          ...item
        }));
        this.page.total = res.total;
      } else {
        uni.showToast({ title: res.msg || '加载失败', icon: 'none' });
      }
    } catch (error) {
      console.error('加载陪诊师失败', error);
      uni.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      this.loading = false;
    }
  },
},
    // 格式化性别显示
    formatGender(gender) {
      return gender === "0" ? '男' : (gender === "1" ? '女' : '未知');
    },

    // 登录校验并加载数据
    async checkLoginAndLoadData() {
      if (!getToken()) {
        uni.showModal({
          title: '提示',
          content: '请先登录后再查看陪诊师列表',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            } else {
              uni.navigateBack();
            }
          }
        });
        return;
      }

      await this.loadTherapists();
      await this.loadRelations();
    },

    // 加载陪诊师数据
    async loadTherapists() {
		 if (this.loading) return;
  const query = {
    pageNum: this.page.pageNum,
    pageSize: this.page.pageSize,
  };

  try {
    const res = await listTherapist(query); // 不传 name，获取全部数据

    if (res.code === 200) {
      let filteredList = res.rows;

      // 如果有关键词，做本地过滤
      if (this.queryParams.name) {
        const keyword = this.queryParams.name.toLowerCase().trim();
        filteredList = res.rows.filter(therapist =>
          therapist.name.toLowerCase().includes(keyword)
        );
      }

      this.therapistList = filteredList;
      this.page.total = filteredList.length;
    } else {
      uni.showToast({ title: res.msg || '加载失败', icon: 'none' });
    }
  } catch (error) {
    console.error('加载陪诊师失败', error);
    uni.showToast({ title: '网络错误', icon: 'none' });
  }
},

    // 加载用户预约关系
    async loadRelations() {
      const query = {
        userId: this.getUserId()
      };

      try {
        const res = await listRelation(query);
        console.log('用户预约关系响应:', res);

        if (res.code === 200) {
          this.relationList = res.rows;
        } else {
          uni.showToast({ title: res.msg || '加载预约信息失败', icon: 'none' });

          if (res.code === 401) {
            uni.showToast({ title: '登录过期，请重新登录', icon: 'none' });
            setTimeout(() => {
              removeToken();
              uni.reLaunch({ url: '/pages/login/login' });
            }, 1500);
          }
        }
      } catch (error) {
        console.error('加载预约信息失败', error);
        uni.showToast({ title: '网络错误', icon: 'none' });
      }
    },

    // 获取当前用户ID（模拟）
    getUserId() {
      return 1;
    },

    // 判断该时间段是否已被预约
    isReserved(therapist) {
      if (!this.queryParams.selectedDate || !this.queryParams.selectedTime) return true;
      return this.relationList.some(r =>
        r &&
        r.therapistId === therapist.id &&
        r.selectedDate === this.queryParams.selectedDate &&
        r.selectedTime === this.queryParams.selectedTime
      );
    },

    // 当前用户是否已预约
    hasBooked(therapist) {
      return this.relationList.some(r =>
        r &&
        r.userId === this.getUserId() &&
        r.therapistId === therapist.id &&
        r.selectedDate === this.queryParams.selectedDate &&
        r.selectedTime === this.queryParams.selectedTime
      );
    },

    // 获取按钮文本
    getButtonText(therapist) {
      if (this.hasBooked(therapist)) return '已预约';
      if (this.isReserved(therapist)) return '不可预约';
      return '预约';
    },

    // 处理预约操作
    handleBooking(therapist) {
      const { selectedDate, selectedTime } = this.queryParams;

      if (!selectedDate || !selectedTime) {
        this.showPopup('请先选择日期和时间');
        return;
      }

      uni.navigateTo({
        url: `/pages/service/BookingForm?therapist=${JSON.stringify(therapist)}&selectedDate=${selectedDate}&selectedTime=${selectedTime}`
      });
    },

    // 显示弹窗
    showPopup(message) {
      this.popupMessage = message;
      this.isPopupVisible = true;
    },
    closePopup() {
      this.isPopupVisible = false;
      this.popupMessage = '';
    },

    // 日期选择事件
    onDateChange(e) {
      const date = e.detail.value;
      this.queryParams.selectedDate = date;
      this.page.pageNum = 1;
      this.loadTherapists();
      this.loadRelations();
    },

    // 时间选择事件
    onTimeChange(e) {
      const time = e.detail.value;
      this.queryParams.selectedTime = time;
      this.page.pageNum = 1;
      this.loadTherapists();
      this.loadRelations();
    },

    // 下拉加载更多
    loadMore() {
      if (!this.hasMore) return;
      this.page.pageNum += 1;
      this.loadTherapists();
    }
  }
};
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
}

/* 搜索和筛选区域 */
.filter-section {
  background-color: #fff;
  padding: 20rpx;
  position: sticky;
  top: 0;
  z-index: 1;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
}

.search-input {
  flex: 1;
  height: 72rpx;
  background: #f5f5f5;
  border-radius: 36rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.search-btn {
  margin-left: 20rpx;
  width: 120rpx;
  height: 72rpx;
  line-height: 72rpx;
  text-align: center;
  background: #4B7BFF;
  color: #fff;
  border-radius: 36rpx;
  font-size: 28rpx;
}

.date-time-picker {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
}

.picker-item {
  flex: 1;
  margin: 0 10rpx;
}

.picker-content {
  background: #f5f5f5;
  padding: 20rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
}

.picker-label {
  color: #666;
  font-size: 26rpx;
  margin-right: 20rpx;
}

.picker-value {
  color: #333;
  font-size: 26rpx;
}

/* 陪诊师列表 */
.therapist-list {
  padding: 20rpx;
}

.therapist-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.therapist-info {
  margin-bottom: 20rpx;
}

.basic-info {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.tag {
  font-size: 24rpx;
  color: #666;
  background: #f5f5f5;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  margin-right: 16rpx;
}

.contact-info {
  font-size: 26rpx;
  color: #666;
}

.action-area {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.action-btn {
  width: 160rpx;
  height: 64rpx;
  line-height: 64rpx;
  text-align: center;
  border-radius: 32rpx;
  font-size: 26rpx;
}

.btn-primary {
  background: #4B7BFF;
  color: #fff;
}

.btn-disabled {
  background: #ccc;
  color: #fff;
}

.btn-booked {
  background: #FF4D4F;
  color: #fff;
}

/* 弹窗样式 */
.popup-content {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  width: 560rpx;
}

.popup-message {
  font-size: 30rpx;
  color: #333;
  text-align: center;
  margin-bottom: 30rpx;
}

.popup-input {
  height: 80rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-bottom: 30rpx;
  font-size: 28rpx;
}

.popup-buttons {
  display: flex;
  justify-content: space-between;
}

.popup-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin: 0 10rpx;
}

.btn-default {
  background: #f5f5f5;
  color: #666;
}
</style>